//
//  ShopConditionViewController.m
//  CarManager
//
//  Created by 王森林 on 2019/1/24.
//  Copyright © 2019年 王森林. All rights reserved.
//

#import "ShopConditionViewController.h"

@interface ShopConditionViewController ()
@property  (nonatomic, strong) NSMutableArray *bodyAry; //座数选择
@property  (nonatomic, strong) NSMutableArray *seatNumAry; //车身选择
@property  (nonatomic, strong) NSArray *priceAry; //价位选择
@property  (nonatomic, strong) NSArray *bodyAllAry; //座数选择
@property  (nonatomic, strong) NSArray *seatNumAllAry; //车身选择
@property  (nonatomic, strong) NSString *jb0000; //级别，如suv、mpv，（需从代码表读取）
@property  (nonatomic, strong) NSString *csjg00; //车身结构，如5门5座（需从代码表读取）
@property  (nonatomic, strong) NSString *zdjgmin; //最低终端价格
@property  (nonatomic, strong) NSString *zdjgmax; //最高终端价格

@property  (nonatomic, strong) UIButton *csPreBtn;
@property  (nonatomic, strong) UIButton *jbPreBtn;
@property  (nonatomic, strong) UIButton *pricePreBtn;
@end

#define JBTAG 1000
#define CSTAG 10000
#define PRICETAG 10000
@implementation ShopConditionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.jb0000 = @"";
    self.csjg00 = @"";
    self.zdjgmax = @"";
    self.zdjgmin = @"";

 
//    [self fetchDataFromNet];
    // Do any additional setup after loading the view.
}


- (void)initAll
{
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.mainTableView.backgroundColor = [UIColor whiteColor];
//    self.mainTableView.hidden = YES;
    [self createUI];
    [self.bodyAry removeAllObjects];
    [self.seatNumAry removeAllObjects];
    [self fetchDataFromNet];
    self.mainTableView.mj_header = [Custom_Mjfresh mj_customMjfreshHeaderSetting:^{
        [self fetchDataFromNet];
    }];
    
    
}


- (void)fetchDataFromNet
{
    //座数
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"DICTIONARIES_ID"],
                             @"DICTIONARIES_ID":@"7408ec459ab74b958a8670cdf0a0e7a1"
                             
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_7 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
         [self.mainTableView.mj_header endRefreshing];
        [self.bodyAry  removeAllObjects];
        NSDictionary *resultDict  = response;
        NSArray *ary = [resultDict objectForKey:@"list"];
        if (ary != nil && ![ary isKindOfClass:[NSNull class]] && ary.count != 0)
        {
            self.bodyAllAry = [NSArray arrayWithArray:[resultDict objectForKey:@"list"]];
            self.bodyAry = [[NSMutableArray alloc] init];
            [self.bodyAry addObject:@"不限"];
            [self.bodyAllAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.bodyAry addObject:[obj objectForKey:@"name"]];
            }];
//            NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1]; // 组数
//            [self.mainTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
            
        }
        if (self.seatNumAry.count  > 0 && self.bodyAry.count > 0) {
            self.priceAry = @[@"不限",@"20-30万",@"30-50万",@"50-80万",@"80万以上"];
            [self.mainTableView  reloadData];
        }
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
             [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    
    //车身
    NSDictionary *params1 = @{
                              @"FKEY":[CommonMethod createMD5Key:@"DICTIONARIES_ID"],
                              @"DICTIONARIES_ID":@"ba32f6fea4274c099175fa7a857cfd04"
                              
                              };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_7 params:params1 md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        [self.mainTableView.mj_header endRefreshing];
        [self.seatNumAry  removeAllObjects];
        NSDictionary *resultDict  = response;
        NSArray *ary = [resultDict objectForKey:@"list"];
        if (ary != nil && ![ary isKindOfClass:[NSNull class]] && ary.count != 0)
        {
            self.seatNumAllAry = [NSArray arrayWithArray:[resultDict objectForKey:@"list"]];
            self.seatNumAry = [[NSMutableArray alloc] init];
            [self.seatNumAry addObject:@"不限"];
            [self.seatNumAllAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.seatNumAry addObject:[obj objectForKey:@"name"]];
            }];
//            NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:0]; // 组数
//            [self.mainTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
            
        }
        
        if (self.seatNumAry.count  > 0 && self.bodyAry.count > 0) {
            self.priceAry = @[@"不限",@"20-30万",@"30-50万",@"50-80万",@"80万以上"];
            [self.mainTableView  reloadData];
        }
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    
}

- (void)handleResetAction:(id)sender
{
    self.jb0000 = @"";
    self.csjg00 = @"";
    self.zdjgmax = @"";
    self.zdjgmin = @"";
    self.jbPreBtn = nil;
    self.csPreBtn = nil;
    self.pricePreBtn = nil;
    self.priceIndex = -1;
     self.jb0000Index = -1;
     self.csjg00Index = -1;
    [self.mainTableView  reloadData];
    
}

- (void)handleSureAction:(id)sender
{
    if (self.jbPreBtn) {
        NSInteger tag  = self.jbPreBtn.tag - JBTAG;
        if (tag != 0) {
            NSString *title  = self.jbPreBtn.titleLabel.text;
           __block NSDictionary *dict = nil;
            [self.seatNumAllAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([[obj objectForKey:@"name"] isEqualToString:title]) {
                    dict = obj;
                }
            }];
            self.jb0000 = [dict objectForKey:@"bianma"];
        } else {
            self.jb0000 = @"";
        }
    }
    
    if (self.csPreBtn) {
        NSInteger tag  = self.csPreBtn.tag - CSTAG;
        if (tag != 0) {
            NSString *title  = self.csPreBtn.titleLabel.text;
            __block NSDictionary *dict = nil;
            [self.bodyAllAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([[obj objectForKey:@"name"] isEqualToString:title]) {
                    dict = obj;
                }
            }];
            self.csjg00 = [dict objectForKey:@"bianma"];
        } else {
            self.csjg00 = @"";
            
        }
    }
    
    if (self.pricePreBtn) {
        NSInteger tag  = self.pricePreBtn.tag - PRICETAG;
        switch (tag) {
            case 0:
            {
                
                self.zdjgmax = @"";
                self.zdjgmin = @"";
            }
                break;
            case 1:
            {
                self.zdjgmax = @"30";
                self.zdjgmin = @"20";
                
            }
                break;
            case 2:
            {
                self.zdjgmax = @"50";
                self.zdjgmin = @"30";
                
            }
                break;
            case 3:
            {
                self.zdjgmax = @"80";
                self.zdjgmin = @"50";
                
            }
                break;
            case 4:
            {
                self.zdjgmax = @"10000";
                self.zdjgmin = @"80";
                
            }
                break;
                
            default:
                break;
        }

    }
    
    
    if (self.resultBlock) {
        self.resultBlock(self.jb0000, self.csjg00, self.zdjgmin, self.zdjgmax);
    }
}

- (void)handleSelectJBAction:(id)sender
{
    UIButton *btn = sender;
    self.jb0000Index  = btn.tag - JBTAG-1;
    if (!btn.selected) {
        btn.selected = YES;
        btn.layer.borderColor = [UIColor redColor].CGColor;
        btn.layer.borderWidth = 1;
        
    } else {
        btn.selected = NO;
        btn.layer.borderWidth = 0;
    }
  
    if (self.jbPreBtn) {
        if (self.jbPreBtn == btn) {
            
        } else  {
            self.jbPreBtn.selected = NO;
            self.jbPreBtn.layer.borderWidth = 0;
            
        }
      
    
    }
    self.jbPreBtn = btn;
    
}

- (void)handleSelectCSAction:(id)sender
{
    
    UIButton *btn = sender;
     self.csjg00Index  = btn.tag - CSTAG-1;
    if (!btn.selected) {
        btn.selected = YES;
        btn.layer.borderColor = [UIColor redColor].CGColor;
        btn.layer.borderWidth = 1;
        
    } else {
        btn.selected = NO;
        btn.layer.borderWidth = 0;
    }
    
    if (self.csPreBtn) {
        if (self.csPreBtn == btn) {
        } else  {
            self.csPreBtn.selected = NO;
            self.csPreBtn.layer.borderWidth = 0;
        }
        
        
    }
    self.csPreBtn = btn;
}

//价格
- (void)handleSelectPriceAction:(id)sender
{
    
    UIButton *btn = sender;
     self.priceIndex  = btn.tag - PRICETAG-1;
    if (!btn.selected) {
        btn.selected = YES;
        btn.layer.borderColor = [UIColor redColor].CGColor;
        btn.layer.borderWidth = 1;
        
    } else {
        btn.selected = NO;
        btn.layer.borderWidth = 0;
    }
    
    if (self.pricePreBtn) {
        if (self.pricePreBtn == btn) {
        } else  {
            self.pricePreBtn.selected = NO;
            self.pricePreBtn.layer.borderWidth = 0;
        }
        
        
    }
    self.pricePreBtn = btn;
}


- (void)createUI
{
    for (UIView *view in self.view.subviews) {
        if (![view isKindOfClass:[UITableView class]]) {
            [view removeFromSuperview];
        }
        
    }
 
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame)-55, BOUNDWIDTH, 0.5)];
    lineLabel.backgroundColor = Common_SepeColor;
    [self.view addSubview:lineLabel];
    
    UIButton *resetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    resetBtn.frame = CGRectMake(0, CGRectGetHeight(self.view.frame)-55, 80, 55);
    [resetBtn setTitle:@"重置" forState:UIControlStateNormal];
    [resetBtn setTitleColor:Common_TextColor forState:UIControlStateNormal];
    resetBtn.titleLabel.font = FONT_SIZE(15);
    [resetBtn addTarget:self action:@selector(handleResetAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:resetBtn];
    
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame = CGRectMake(80, CGRectGetHeight(self.view.frame)-55,  BOUNDWIDTH  - 60, 55);
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:Common_TextColor forState:UIControlStateNormal];
    [sureBtn setBackgroundColor:[UIColor  yellowColor]];
    sureBtn.titleLabel.font = FONT_SIZE(15);
    [sureBtn addTarget:self action:@selector(handleSureAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
    
   //[self.mainTableView registerClass:[HomeNoticeCell class] forCellReuseIdentifier:@"HomeNoticeCell"];
    
}

#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}
#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 0;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    switch (section) {
        case 0:
        {
            if (self.seatNumAry.count == 0) {
                return 0;
            } else {
                if (self.seatNumAry.count % 3 == 0) {
                    return 10+50*(self.seatNumAry.count/3);
                } else {
                    
                    return 10+50*(self.seatNumAry.count/3+1);
                }
                
            }
            
        }
            break;
        case 1:
        {
            
            if (self.bodyAry.count == 0) {
                return 0;
            } else {
                if (self.bodyAry.count %3 == 0) {
                    return 10+50*(self.bodyAry.count/3);
                } else {
                    
                    return 10+50*(self.bodyAry.count/3+1);
                }
                
            }
            
        }
            break;
        case 2:
        {
            if (self.priceAry.count == 0 ) {
                return 0;
            } else {
                if (self.priceAry.count %3 == 0) {
                    return 10+50*(self.priceAry.count/3);
                } else {
                    
                    return 10+50*(self.priceAry.count/3+1);
                }
                
            }
          
            
        }
            break;
            
        default:
            return 0;
            break;
    };
}



- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *headView = [UIView new];
    UILabel  *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, (100-15)/2, 80, 15)];
    titleLabel.text = @"车身";
    titleLabel.font = FONT_SIZE(15);
    titleLabel.textColor = Common_TextColor;
    [headView addSubview:titleLabel];
    
    float btnWidth = (BOUNDWIDTH - 100 - 50)/3;
    float btnHeight = 40;
    switch (section) {
        case 0:
        {
              titleLabel.text = @"车身";
            [self.seatNumAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(115+idx%3*(btnWidth+10), 10+ 50*(idx/3), btnWidth, btnHeight);
                [btn setTitle: obj forState:UIControlStateNormal];
                [btn setTitleColor:Common_TextColor forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
                btn.titleLabel.font = FONT_SIZE(14);
                btn.layer.cornerRadius = 5;
                btn.layer.masksToBounds = YES;
                [btn setBackgroundColor:Common_BackgroundGrayColor];
                btn.tag = JBTAG+idx;
                [btn addTarget:self action:@selector(handleSelectJBAction:) forControlEvents:UIControlEventTouchUpInside];
              
              
             
                if (self.jb0000Index !=  -1) {
                    if ((btn.tag - JBTAG) == (self.jb0000Index +1) ){
                        btn.selected = YES;
                        btn.layer.borderColor = [UIColor redColor].CGColor;
                        btn.layer.borderWidth = 1;
                        self.jbPreBtn = btn;
                    }
                } else {
                    if (!self.jbPreBtn && idx == 0) {
                        
                        btn.selected = YES;
                        btn.layer.borderColor = [UIColor redColor].CGColor;
                        btn.layer.borderWidth = 1;
                        self.jbPreBtn = btn;
                        
                    }
                    if (self.jbPreBtn.tag == btn.tag) {
                        btn.selected = YES;
                        btn.layer.borderColor = [UIColor redColor].CGColor;
                        btn.layer.borderWidth = 1;
                        self.jbPreBtn = btn;
                    }
                    
                }
             
                [headView addSubview:btn];
            }];
            
        }
            break;
        case 1:
        {
              titleLabel.text = @"座数";
            [self.bodyAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(115+idx%3*(btnWidth+10), 10+ 45*(idx/3), btnWidth, btnHeight);
                [btn setTitle: obj forState:UIControlStateNormal];
                [btn setTitleColor:Common_TextColor forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
                btn.titleLabel.font = FONT_SIZE(14);
                btn.layer.cornerRadius = 5;
                btn.layer.masksToBounds = YES;
                [btn setBackgroundColor:Common_BackgroundGrayColor];
                btn.tag = CSTAG+idx;
                 [btn addTarget:self action:@selector(handleSelectCSAction:) forControlEvents:UIControlEventTouchUpInside];
//                if (!self.csPreBtn && idx == 0) {
//
//                    btn.selected = YES;
//                    self.csPreBtn = btn;
//
//                }
           
                
                if (self.csjg00Index !=  -1) {
                    if ((btn.tag - CSTAG) == (self.csjg00Index +1) ){
                        btn.selected = YES;
                        btn.layer.borderColor = [UIColor redColor].CGColor;
                        btn.layer.borderWidth = 1;
                        self.csPreBtn = btn;
                    }
                } else {
                    if (!self.csPreBtn && idx == 0) {
                        
                        btn.selected = YES;
                        btn.layer.borderColor = [UIColor redColor].CGColor;
                        btn.layer.borderWidth = 1;
                        self.csPreBtn = btn;
                        
                    }
                    
                    if (self.csPreBtn.tag == btn.tag) {
                        btn.selected = YES;
                        btn.layer.borderColor = [UIColor redColor].CGColor;
                        btn.layer.borderWidth = 1;
                        self.csPreBtn = btn;
                    }
                    
                }
                [headView addSubview:btn];
            }];

        }
            break;
        case 2:
        {
             titleLabel.text = @"价格";
            [self.priceAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(115+idx%3*(btnWidth+10), 10+ 45*(idx/3), btnWidth, btnHeight);
                [btn setTitle: obj forState:UIControlStateNormal];
                [btn setTitleColor:Common_TextColor forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
                btn.titleLabel.font = FONT_SIZE(14);
                btn.layer.cornerRadius = 5;
                btn.layer.masksToBounds = YES;
                [btn setBackgroundColor:Common_BackgroundGrayColor];
                 btn.tag = PRICETAG+idx;
                 [btn addTarget:self action:@selector(handleSelectPriceAction:) forControlEvents:UIControlEventTouchUpInside];
//                if (!self.pricePreBtn && idx == 0) {
//
//                    btn.selected = YES;
//                    self.pricePreBtn = btn;
//
//                }
             
                
                if (self.priceIndex !=  -1) {
                    if ((btn.tag - PRICETAG) == (self.priceIndex +1) ){
                        btn.selected = YES;
                        btn.layer.borderColor = [UIColor redColor].CGColor;
                        btn.layer.borderWidth = 1;
                        self.pricePreBtn = btn;
                    }
                } else {
                    if (!self.pricePreBtn && idx == 0) {
                        
                        btn.selected = YES;
                        btn.layer.borderColor = [UIColor redColor].CGColor;
                        btn.layer.borderWidth = 1;
                        self.pricePreBtn = btn;
                        
                    }
                    
                    if (self.pricePreBtn.tag == btn.tag) {
                        btn.selected = YES;
                        btn.layer.borderColor = [UIColor redColor].CGColor;
                        btn.layer.borderWidth = 1;
                         self.pricePreBtn = btn;
                    }
                }
                [headView addSubview:btn];
            }];
            
        }
            break;
            
        default:
            break;
    }
    
    return headView;
}


//- (NSArray *)priceAry
//{
//    if (!_priceAry) {
//        _priceAry = @[@"不限",@"20-30万",@"30-50万",@"50-80万",@"80万以上"];
//    }
//    return _priceAry;
//}



@end
